package com.zks.nio;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PlainNioClient {
    public static void main(String[] args) throws Exception {
        SocketChannel socketChannel=SocketChannel.open();
        socketChannel.configureBlocking(false);
        Selector selector= Selector.open();
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        socketChannel.connect(new InetSocketAddress("localhost",8034));

        while(true){
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            for(SelectionKey selectionKey:selectionKeys){
                if(selectionKey.isConnectable()){//与服务器端连接就绪
                    SocketChannel client=(SocketChannel)selectionKey.channel();
                    if(client.isConnectionPending()){//判断此通道上是否正在进行连接操作。
                                              // 当且仅当已在此通道上发起连接操作，
                        // 但是尚未通过调用 finishconnect 方法完成连接时才返回 true

                        client.finishConnect();
                        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                        byteBuffer.put("client 连接成功".getBytes());
                        byteBuffer.flip();
                        client.write(byteBuffer);

                        ExecutorService executorService = Executors.newSingleThreadExecutor();
                        executorService.submit(()->{
                            while(true){
                                byteBuffer.clear();
                                InputStreamReader inputStreamReader=new InputStreamReader(System.in);
                                BufferedReader bf=new BufferedReader(inputStreamReader);
                                String message=bf.readLine();
                                byteBuffer.put(message.getBytes());
                                byteBuffer.flip();
                                client.write(byteBuffer);

                            }
                        });
                        client.configureBlocking(false);
                        client.register(selector,SelectionKey.OP_READ);
                    }

                }else if(selectionKey.isReadable()){
                   SocketChannel clent=(SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                    int count=clent.read(byteBuffer);

                    if(count>0){
                        String me=new String(byteBuffer.array(),0,count);
                        System.out.println(me);

                    }
                }


            }
            selectionKeys.clear();


        }

    }
}
